<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回到顶部-案例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            height: 3000px;
        }

        .header {
            width: 100%;
            height: 80px;
            display: flex;
            justify-content: center;
            /* 调整主轴对齐方向 */
            align-items: center;
            /* 调整侧轴对齐方向 */
            font-size: 30px;
            color: #fff;
            background-color: skyblue;

            transition:top .5s linear ;

            position: fixed;
            /* 脱离浏览器当前窗口 */
            top: -80px;
            left: 0;
        }

        .goTop {
            width: 50px;
            height: 50px;
            background-color: pink;
            font-size: 20px;
            text-align: center;
            line-height: 25px;
            color: #fff;
            cursor: pointer;
            position: fixed;
            bottom: 50px;
            right: 50px;

            display: none;
        }
    </style>
</head>

<body>
    <div class="header">顶部通栏</div>
    <div class="goTop">回到顶部</div>

    <script>
        //1.获取元素
        var header = document.querySelector('.header')
        var goTop = document.querySelector('.goTop')

        //2.绑定滚动事件
        window.onscroll = function () {
            //2-1. 获取浏览器卷去的高度（浏览器卷去尺寸）
            var height = document.documentElement.scrollTop || document.body.scrollTop

            //2-2. 判断卷去的高度
            if (height >= 300) {
                //显示（操作元素的样式）
                header.style.top = '0px'
                goTop.style.display = 'block'
            } else {
                //隐藏
                header.style.top = '-200px'
                goTop.style.display = 'none'
            }
        }
        //3.绑定点击事件
        goTop.onclick=function(){
            //3-1 让页面滚动回到顶部（浏览器滚动到）
            window.scrollTo({
                top:0,
                behavior:'smooth'
            })
        }
    </script>
</body>

</html>